package com.lyf.security.config.datasource.sources;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @AUTHOR LYF
 * @DATE 2022/1/19
 * @VERSION 1.0
 * @DESC cap数据库配置
 *
 */
@EnableTransactionManagement
//@Component
@Configuration // @Component 会报错
@EnableJpaRepositories(entityManagerFactoryRef = "capEntityManagerFactory",
                       transactionManagerRef = "capTransactionManager",
                       basePackages = {"com.lyf.data.structure.jpa.repository.cap"})//配置Jpa信息
public class CapDataSourceConfig {
    @Autowired
    @Qualifier("capDataSource")
    DataSource capDataSource;

    // 配置实体管理的地方
    @Primary// 实体管理需主配？
    @Bean(name = "capEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean capEntityManagerFactory(EntityManagerFactoryBuilder builder){
        return builder.dataSource(capDataSource)
                .packages("com.lyf.data.structure.jpa.entity.cap")
                .persistenceUnit("capPersistenceUnit")
                .build();
    }

    // 配置事务管理
    @Bean
    TransactionManager capTransactionManager(EntityManagerFactoryBuilder builder){
//       return new JpaTransactionManager(capEntityManagerFactory(builder).getObject());
    //    Method annotated with @Bean is called directly. Use dependency injection instead.
         return new JpaTransactionManager(capEntityManagerFactory(builder).getObject());
    }


}
